package com.meisupic.copyright.controller;

import static com.meisupic.copyright.common.Constants.AUTH_TYPE_ENTERPRISE;
import static com.meisupic.copyright.common.Constants.AUTH_TYPE_PERSON;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.meisupic.copyright.common.AuthProcessEnum;
import com.meisupic.copyright.common.ImageStatusEnum;
import com.meisupic.copyright.domain.po.RealNameAuth;
import com.meisupic.copyright.domain.po.Users;
import com.meisupic.copyright.domain.vo.RealNameAuthResponVo;
import com.meisupic.copyright.domain.vo.RealNameAuthVo;
import com.meisupic.copyright.service.IRealNameAuthService;
import com.meisupic.copyright.service.ISalesService;
import com.meisupic.copyright.service.IUserService;
import com.meisupic.copyright.support.EhcacheHelper;
import com.meisupic.copyright.support.Message;
import com.meisupic.copyright.util.BeanMapper;
import com.meisupic.copyright.util.StringUtil;
import com.meisupic.copyright.util.ValidatorUtil;
import com.meisupic.copyright.validategroups.EnterpriseAuthGroup;
import com.meisupic.copyright.validategroups.PersonAuthGroup;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * creation wuxun
 *
 * @version V1.0
 * @Description: 实名认证控制器
 * @date 2018/1/14 19:17
 */
@Controller
@RequestMapping("/copyright/realNameAuth")
public class RealNameAuthController extends BaseController {

  @Autowired
  private IRealNameAuthService realNameAuthService;

  @Autowired
  private IUserService userService;

  @Autowired
  private ISalesService salesService;

  @Value("${baidu.appid}")
  private String APP_ID;

  @Value("${baidu.apiKey}")
  private String API_KEY;

  @Value("${baidu.secretKey}")
  private String SECRET_KEY;

  @Value("${oss.host}")
  private String ossHost;

  @RequestMapping("/info")
  @ResponseBody
  public Message<RealNameAuthResponVo> getRealNameAuth() {
    RealNameAuth realNameAuth = realNameAuthService.findByUserId(getUserId());
    RealNameAuthResponVo responVo = new RealNameAuthResponVo();
    if (!StringUtil.isEmpty(realNameAuth)) {
      responVo = BeanMapper.map(realNameAuth, RealNameAuthResponVo.class);
    }
    return Message.success(responVo);
  }


  @PostMapping("/person/save")
  @ResponseBody
  public Message savePerson(
      @RequestBody @Validated(value = PersonAuthGroup.class) RealNameAuthVo realNameAuthVO)
      throws IOException {
    Integer[] types = {1, 2, 3, 4, 9};
    if (!Arrays.asList(types).contains(realNameAuthVO.getDocumentType())) {
      return Message.error("证件类型错误");
    }
    switch (realNameAuthVO.getDocumentType()) {
      case 1:
        if (!ValidatorUtil.isIDCardNo(realNameAuthVO.getDocumetNo())) {
          return Message.error("身份证号码不合法");
        }
        break;
      default:
        break;
    }
    if(realNameAuthVO.getLongTermEffective()==null){
      realNameAuthVO.setLongTermEffective(0);
    }
    realNameAuthVO.setAuditStatus(AuthProcessEnum.commited);
    realNameAuthVO.setAuthType(AUTH_TYPE_PERSON);
    realNameAuthVO.setCreatorId(getUserId());
    realNameAuthVO.setModifierId(getUserId());

    RealNameAuth update_entity = BeanMapper.map(realNameAuthVO, RealNameAuth.class);
    realNameAuthService.personAuthAndSave(update_entity);
    return Message.success(true);
  }

  @PostMapping("/enterprise/save")
  @ResponseBody
  public Message saveEnterprise(
      @RequestBody @Validated(value = EnterpriseAuthGroup.class) RealNameAuthVo realNameAuthVO) {

    if (AUTH_TYPE_ENTERPRISE.equals(realNameAuthVO.getAuthType())) {
      Integer[] types = {5, 6, 7, 8, 9};
      if (!Arrays.asList(types).contains(realNameAuthVO.getDocumentType())) {
        return Message.error("证件类型错误");
      }
      switch (realNameAuthVO.getDocumentType()) {
        case 5:
          if (!ValidatorUtil.isUnicode(realNameAuthVO.getDocumetNo())) {
            Message.error("社会统一信用代码错误");
          }
          break;
        case 6:
          if (!ValidatorUtil.isOrgCode(realNameAuthVO.getDocumetNo())) {
            Message.error("组织机构代码错误");
          }
          break;
        default:
          break;
      }

    } else {
      return Message.error("实名认证类型不正确");
    }
    if(realNameAuthVO.getLongTermEffective()==null){
      realNameAuthVO.setLongTermEffective(0);
    }
    realNameAuthVO.setAuditStatus(AuthProcessEnum.commited);
    realNameAuthVO.setCreatorId(getUserId());
    realNameAuthVO.setModifierId(getUserId());
    RealNameAuth update_entity = BeanMapper.map(realNameAuthVO, RealNameAuth.class);
    realNameAuthService.enterpriseAuthAndSave(update_entity);
    return Message.success(true);
  }


  @GetMapping("ocrIdCard")
  @ResponseBody
  public Message ocrIdCard(String imageUrl, String idCardSide) {
    HashMap<String, String> options = new HashMap<String, String>();
    options.put("detect_direction", "true");
    options.put("detect_risk", "false");

    try {
      URL url = new URL(imageUrl);
      byte[] image = IOUtils.toByteArray(url);

      AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
      JSONObject res = client.idcard(image, idCardSide, options);
      logger.info(res.toString());
      String imageStatus = res.getString("image_status");

      if (!"normal".equals(imageStatus)) {
        ImageStatusEnum imageStatusEnum = Enum.valueOf(ImageStatusEnum.class, imageStatus);
        return Message.error("识别出错：" + imageStatusEnum.getDesc());
      }
      return Message.success(res.toString());
    } catch (IOException e) {
      logger.error("身份证识别出错", e);
      return Message.error("识别出错，请重试");
    } catch (JSONException e) {
      logger.error("身份证识别解析返回json错误", e);
      return Message.error("无法识别，请重新上传");
    }
  }

  @GetMapping("ocrBusinessLicense")
  @ResponseBody
  public Message ocrBusinessLicense(String imageUrl) {
    HashMap<String, String> options = new HashMap<String, String>();
    try {
      URL url = new URL(imageUrl);
      byte[] image = IOUtils.toByteArray(url);
      AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
      JSONObject res = client.businessLicense(image, options);

      return Message.success(res.toString());
    } catch (MalformedURLException e) {
      logger.error("营业执照识别出错", e);
      return Message.error("识别出错，请重试");
    } catch (IOException e) {
      logger.error("营业执照识别出错", e);
      return Message.error("识别出错，请重试");
    }

  }

  /**
   * 检查用户是否已经填写实名认证
   */
  @GetMapping("hasRealnameAuth")
  @ResponseBody
  public Message hasRealnameAuth() {
    Users users = userService.findById(getUserId());
    RealNameAuth realNameAuth = realNameAuthService.findByUserId(getUserId());
    if (realNameAuth == null) {
      return Message.success(3);
    }else if(StringUtil.isEmpty(users.getMobile())&&StringUtil.isEmpty(realNameAuth.getMobile())&& users.getHuabanUserId()!=null&&users.getHuabanUserId()!=0){
      return Message.success(2);
    }
    return Message.success(4);
  }

  /**
   * 绑定手机号
   * @param mobile
   * @return
   */
  @PostMapping("bindMobile")
  @ResponseBody
  public Message bindMobile(String mobile,String verifyCode){
    Object randomCodeCache = EhcacheHelper.get("randomCodeCache",mobile);
    if(!verifyCode.equals(randomCodeCache.toString())){
      return Message.error("验证码错误");
    }
    userService.updateMobile(mobile,getUserId());
    RealNameAuth realNameAuth = realNameAuthService.findByUserId(getUserId());
    if(realNameAuth!=null){
      realNameAuth.setMobile(mobile);
      realNameAuthService.updateRealNameAuth(realNameAuth);
      return Message.success(1);
    }
    return Message.success(2);
  }

  @GetMapping("/sendBindMobileSms")
  @ResponseBody
  public Message sendBindMobileSms(String mobile){
    int randomCode = StringUtil.getRangeRandomCode(100000,999999);
    EhcacheHelper.put("randomCodeCache", mobile, randomCode);
    String smsContent = "【美素版权】绑定手机号验证码" + randomCode;
    String sendResult = salesService.sendMessage(mobile, smsContent);
    logger.info(smsContent);
    com.alibaba.fastjson.JSONObject resultObject = JSON.parseObject(sendResult);
    if (resultObject.getIntValue("error") == 0) {
      return Message.success("");
    }else {
      return Message.error(resultObject.getString("content"));
    }
  }

  @GetMapping("/pushApplyer")
  @ResponseBody
  public Message pushApplyer(Long id){
    return Message.success(realNameAuthService.pushApplyer(id));
  }
}
